package com.haiyou.common.event.asyc;

import java.util.concurrent.ForkJoinPool;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.SubscriberExceptionContext;
import com.google.common.eventbus.SubscriberExceptionHandler;
import com.haiyou.common.event.AbstractEvent;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: 异步事件
 * @author xingyuan
 * @date 2022年2月15日 下午5:12:16
 */
@Slf4j
public class AsyncEventBuses implements SubscriberExceptionHandler{

	private static final class Lazy {
		private static final AsyncEventBuses instance;
		static {
			instance = new AsyncEventBuses();
		}
	}

	public static AsyncEventBuses getInstance() {
		return Lazy.instance;
	}

	private final AsyncEventBus asyncEventBus;

	private AsyncEventBuses() {
		asyncEventBus = new AsyncEventBus(ForkJoinPool.commonPool(), this);
	}

	@Override
	public void handleException(Throwable exception, SubscriberExceptionContext context) {
		log.error(exception.getMessage(),exception);
	}

	public <T extends AbstractAsyncEventObserver, E extends AbstractEvent> void register(T observer) {
		log.info("register async event observer [{}]", observer);
		asyncEventBus.register(observer);
	}

	public <T extends AbstractAsyncEventObserver, E extends AbstractEvent> void unregister(T observer) {
		log.info("unregister async event observer [{}]", observer);
		asyncEventBus.unregister(observer);
	}

	public <E extends AbstractEvent> void postEvent(E event) {
		
		if(log.isDebugEnabled()) {
			log.debug("post async Event  [{}]", event);
		}
		
		log.info("post async Event  [{}]", event.getClass().getSimpleName());
		
		if(asyncEventBus == null) {
			return ;
		}
		
		asyncEventBus.post(event);
	}

}
